package com.UKIT.airtickets.Service.Handlers

import android.content.Context
import android.widget.Toast
import androidx.room.Room
import com.UKIT.airtickets.Activities.RegistrationActivity
import com.UKIT.airtickets.DB.AppDatabase
import com.UKIT.airtickets.DB.User
import com.UKIT.airtickets.DB.UserSettings
import com.UKIT.airtickets.Service.SettingsApp
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch

class RegistrationHandler(private val context: Context) {

    private val db: AppDatabase by lazy {
        Room.databaseBuilder(context.applicationContext, AppDatabase::class.java, "airtickets.db")
            .fallbackToDestructiveMigration()
            .build()
    }

    private val coroutineScope = CoroutineScope(Dispatchers.IO)

    fun registerUser(login: String, email: String, password: String) {
        coroutineScope.launch {
            val user = User(login = login, email = email, password = password)

            db.userDao().addUser(user)
            db.userSettingsDao().insertUserSettings(
                UserSettings(
                    user.id,
                    false,
                    "ru",
                    false
                )
            )

            SettingsApp.userId = user.id

            launch(Dispatchers.Main) {
                val toastWrapper = ToastWrapper()
                toastWrapper.showToast(context, "Пользователь успешно зарегистрирован!")

                (context as RegistrationActivity).navigateToAuthorization()
            }
        }
    }

    fun cancelJobs() {
        coroutineScope.coroutineContext.cancelChildren()
    }
}

class ToastWrapper {
    fun showToast(context: Context, message: String) {
        Toast.makeText(context, message, Toast.LENGTH_SHORT).show()
    }
}